package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        log.info("拦截器获取token，值为:{}", token);
        //判空
        if (StringUtils.isEmpty(token)) {
            throw new BaseException("认证失败");
        }

        //判断是否有效
        Map<String, Object> claims = tokenService.parseToken(token);
        log.info("解析token获取claims，值为:{}", claims);
        if (MapUtil.isEmpty(claims)) {
            throw new BaseException("认证失败");
        }

        Object id = claims.get("id");
        long idl = Long.parseLong(id + "");
        log.info("解析claims获取id，值为:{}", idl);
        if (StringUtils.isEmpty(id + "")) {
            throw new BaseException("认证失败");
        }

        //将数据存入线程
        UserThreadLocal.set(idl);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
